<?php defined('BASEPATH') OR exit('No direct script access allowed');

if ( ! class_exists('Controller'))
{
	class Controller extends CI_Controller {}
}

class Auth extends Controller {

	function __construct()
	{
		parent::__construct();
		$this->load->library('ion_auth');
		$this->load->library('session');
		$this->load->library('form_validation');
		$this->load->database();
		$this->load->helper('url');
	}

	//redirect if needed, otherwise display the user list
	function index() {
		if (!$this->ion_auth->logged_in()) {
			redirect('auth/login', 'refresh');
		} else {
			redirect('client');
		}
	}

	//log the user in
	function login($url)
	{
		if (mb_substr_count($url, "auth/login") > 0) $url = "";

		if (mb_substr_count($url, ".html") > 0) $replace_delimiter = ":"; else $replace_delimiter = ".";

		$this->data['url'] = $url;
		$this->data['title'] = "Login";

		//validate form input
		$this->form_validation->set_rules('email', 'электронная почта', 'required|valid_email');
		$this->form_validation->set_rules('password', 'пароль', 'required');

/*		if ($this->form_validation->run() == true)
		{ //check to see if the user is logging in
			//check for "remember me"
			$remember = (bool) $this->input->post('remember');
			if ($this->ion_auth->login($this->input->post('email'), $this->input->post('password'), $remember))
			{ //if the login is successful
				//redirect them back to the home page
				$this->ion_auth->messages();
				redirect(($url?mb_substr(str_replace($replace_delimiter, "/", $url), 1):$this->config->item('base_url')), 'refresh');
			} else { //if the login was un-successful
				//redirect them back to the login page
				$this->ion_auth->errors();
				redirect('auth/login/'.$url, 'refresh'); //use redirects instead of loading views for compatibility with MY_Controller libraries
			}
		} else {
/*			if ($_SERVER['REQUEST_METHOD'] == "POST" ) {
				if (validation_errors()) $this->session->set_flashdata('msg', validation_errors());
				redirect('auth/login'.$url);
			} else { */
				//$this->ion_auth_model->logout();
				
				//dump($this->input->post());
				
				$form = new jQuickForm('auth_login');
				$form->setLabel('Авторизация');
				$fieldset = $form->insertFieldset();
				
				$gr = $fieldset->insertGroup()->addClass('col col2');
				$email = $gr->insertInputText('email')->setLabel('Электронная почта');
				$email->addRule('callback', 'Не верный формат поля', array('callback' => 'validate_email'), HTML_QuickForm2_Rule::CLIENT);
				$email->addRule('callback', 'Не верный формат поля', array('callback' => 'validate_email'), HTML_QuickForm2_Rule::SERVER);
				$email->addRuleRequired();
					
				$password = $gr->insertInputPassword('password')->setLabel('Пароль')->setAttribute('autocomplete', 'off');
				$password->addRuleRequired();
				
				$gr2 = $fieldset->insertGroup()->addClass('chk');
				$gr2->insertInputCheckbox('remember', 'Запомнить меня')->setValue(1);

				if ($this->input->server('REQUEST_METHOD') == "POST") {
					if ($form->validate()) {
							$remember = (bool) $this->input->post('remember');
							if ($this->ion_auth->login($this->input->post('email'), $this->input->post('password'), $remember)) {
								redirect(($url?mb_substr(str_replace($replace_delimiter, "/", $url), 1):$this->config->item('base_url')), 'refresh');
							} else {
								$data['msg'] = "Ошибка авторизации, проверьте логин и пароль.";
							}
					}
				}
				
				$form->insertInputSubmit('Войти');
				$form->insertStatic('<p style="text-align: center;"><a class="blue-link" href="/auth/forgot_password/">Напомнить пароль</a> | <a class="blue-link" href="/auth/signup/">Регистрация</a></p>');
				
				$form->addDataSource(new HTML_QuickForm2_DataSource_Array($this->input->post()));
				$data['form'] = $form."";
				$data['js'] = jQuickForm::js()->getJsAll();
				
				if ($this->input->server('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest') {
					$this->load->view('auth/login', $data);
				} else {
					$this->layout->view('auth/login', $data);
				}
//			}
		//}
	}

	//log the user out
	function logout()
	{
		$this->data['title'] = "Logout";

		$cookie = array(
			'name'   => 'firsttime',
			'value'  => '0',
			'expire' => '2595000',
			'domain' => '.'.$_SERVER['HTTP_HOST'],
			'path'   => '/'
		);
		set_cookie($cookie);

		//log the user out
		$logout = $this->ion_auth->logout();

		//redirect them back to the page they came from
		redirect('/', 'refresh');
	}

	//forgot password
	function forgot_password()
	{
		$this->form_validation->set_rules('email', 'Email Address', 'required');
		if ($this->form_validation->run() == false)
		{
			//setup the input
			$this->data['email'] = array('name' => 'email',
				'id' => 'email',
			);
			//set any errors and display the form
			$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
			$this->layout->view('auth/forgot_password', $this->data);
		}
		else
		{
			//run the forgotten password method to email an activation code to the user
			$forgotten = $this->ion_auth->forgotten_password($this->input->post('email'));

			if ($forgotten)
			{ //if there were no errors
				$this->session->set_flashdata('message', $this->ion_auth->messages());
				redirect("auth/login", 'refresh'); //we should display a confirmation page here instead of the login page
			}
			else
			{
				$this->session->set_flashdata('message', $this->ion_auth->errors());
				redirect("auth/forgot_password", 'refresh');
			}
		}
	}

	//reset password - final step for forgotten password
	public function reset_password($code)
	{
		$reset = $this->ion_auth->forgotten_password_complete($code);

		if ($reset)
		{  //if the reset worked then send them to the login page
			$this->session->set_flashdata('message', $this->ion_auth->messages());
			redirect("auth/login", 'refresh');
		}
		else
		{ //if the reset didnt work then send them back to the forgot password page
			$this->session->set_flashdata('message', $this->ion_auth->errors());
			redirect("auth/forgot_password", 'refresh');
		}
	}

	//activate the user
	function activate($id, $code=false)
	{
		if ($code !== false)
			$activation = $this->ion_auth->activate($id, $code);
		else if ($this->ion_auth->is_admin())
			$activation = $this->ion_auth->activate($id);


		if ($activation)
		{
			//redirect them to the auth page
			$this->session->set_flashdata('message', $this->ion_auth->messages());
			redirect("auth", 'refresh');
		}
		else
		{
			//redirect them to the forgot password page
			$this->session->set_flashdata('message', $this->ion_auth->errors());
			redirect("auth/forgot_password", 'refresh');
		}
	}

	//create a new user
	function signup() {
		if ($this->ion_auth->logged_in()) redirect('/');
		$this->ion_auth_model->edit(0);
	}

	function _get_csrf_nonce()
	{
		$this->load->helper('string');
		$key = random_string('alnum', 8);
		$value = random_string('alnum', 20);
		$this->session->set_flashdata('csrfkey', $key);
		$this->session->set_flashdata('csrfvalue', $value);

		return array($key => $value);
	}

	function _valid_csrf_nonce()
	{
		if ($this->input->post($this->session->flashdata('csrfkey')) !== FALSE &&
				$this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue'))
		{
			return TRUE;
		}
		else
		{
			return FALSE;
		}
	}
	function checkout() {
		if ($this->input->server('HTTP_X_REQUESTED_WITH') != 'XMLHttpRequest' || $this->input->server('REQUEST_METHOD') != "POST") {
			die("Hack attempt");
		} else {
			if (!$this->ion_auth->logged_in()) {
				if ($this->input->post('email') != "") {
					$result = $this->db->select()->from('users')->where('email', $this->input->post('email'))->get()->row_array();
					if (sizeof($result) > 0) {
						$data['result'] = true;
					} else {
						$data['result'] = false;
					}
				} else {
					$data['result'] = false;
				}
				echo json_encode($data);
			} else {
				die("Hack attempt");
			}
		}
	}
}